var app=getApp();
var ux = require('../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {   
    sum: 0,
    remaks:'',
    tongyi:2, 
    dotNull:1,
    dot:{},
    song: 2,
    orderId:null,
    address:{},
    banrd:{},
    order:{},
    list:[],
    yaoUrl:"/api/orders/yaoFreeConfirmOrder.do",
    submitUrl:"/api/orders/yEConfirmOrder.do",
    dotUrl:"/api/dot/getLatelyDot.do",
    action:"/api/balance/getOrderInfos.do",
	submit:"{{submit}}"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var self = this;
    this.setData({
      banrdId: wx.getStorageSync("banrdId")
    });
    ux.login(function (protocol) {
      if (protocol.success) {
        wx.setStorageSync("userInfo", protocol.data.userInfo);
        wx.setStorageSync("token", protocol.data.token);
        self.setData({
          userInfo: protocol.data.userInfo
        })
      }
    });
      if(options.orderId){
       this.setData({
         orderId:options.orderId
       })
      }
    var params = { orderId: this.data.orderId}
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    ux.request(this.data.action, params,function(protocol){
      wx.hideLoading();
				self.setData({
          sum: ux.acAdd(protocol.data.peisong,protocol.data.order.actualPay),
          address: protocol.data.address,
          peisong: protocol.data.peisong,
          banrd: protocol.data.banrd,
          order: protocol.data.order,
          list: protocol.data.list,
        })
		  },true);
  },
  
  onForm:function(event){
	if(this.data.submit){
		  var $this = this;
		  var dataset = event.currentTarget.dataset;
		  ux.request(this.data.submit,detail.value,function(protocol){
				if(protocol.success){
					if(dataset.url){
						wx.redirectTo(dataset.url);
					}
				}
		  },true);
	 }
  },
  
  onTap:function(event){
	  var dataset = event.currentTarget.dataset;
	  var data = this.data;
	  if(dataset.key && dataset.val){
		  data[dataset.key] = dataset.val;
	  }
	  this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

 
  gotoSelectAddress:function(){
      wx.navigateTo({
        url: '/pages/member/tab3/adress/adressList',
      })
    },
  songh:function(){
     this.setData({
       sum: ux.acAdd(this.data.peisong,this.data.order.actualPay),
      song:2
     })
  },
  ziti:function(){
    var self=this;
    if (!this.data.address && !this.data.address.id) {
      self.toast("请配置收获地址");
       return false;
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    var params = { banrdId: this.data.banrdId, adressId:this.data.address.id }
    ux.request(this.data.dotUrl, params, function (protocol) {
      console.log(JSON.stringify(protocol.data.dot));
      wx.hideLoading();
             if(protocol.data.type==1){
               self.setData({
                 dot:protocol.data.dot
               })
               self.setData({
                 sum: self.data.order.actualPay,
                 song: 1
               })
             }else{
               self.setData({
                 sum: ux.acAdd(self.data.peisong, self.data.order.actualPay),
                 song: 2
               })
              self.toast("该品牌还没有自提网点")
             }
    }, true);
    
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  tongyis:function(){
    if(this.data.tongyi==2){
      this.setData({
        tongyi:1
      })
    }else{
      this.setData({
        tongyi: 2
      })
    }
  },
  byFree: function (formId){
    var self = this;
    if (!this.data.address) {
      this.toast("请填写收货地址");
      return false;
    }
    if (this.data.tongyi == 2) {
      this.toast("请认证阅读支付协议并同意");
      return false;
    }
    var parmas = { formId: formId, pfee: this.data.peisong, cityId: this.data.address.cityOrigin, pType: this.data.song, remarks: this.data.remaks, xie: 1, adressId: this.data.address.id, orderId: this.data.order.id };
    if (this.data.song == 1) {
      parmas.dotId = this.data.dot.id;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(self.data.submitUrl, parmas, function (data) {
      wx.hideLoading();
      if (data.data.type == 1) {
        self.toast("提交成功");
        wx.redirectTo({
          url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
        })
      } else {
        wx.redirectTo({
          url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
        })
        self.toast("提交失败")
      }
    })
  },
  tijiaos:function(e){
    let formId = e.detail.formId;
    if(this.data.peisong>0&&this.data.song==2){
      this.yaoFree(formId);
    }else{
      this.byFree(formId);
    }
  },
  yaoFree: function (formId){
    var self = this;
    if (!this.data.address) {
      this.toast("请填写收货地址");
      return false;
    }
    if (this.data.tongyi == 2) {
      this.toast("请认证阅读支付协议并同意");
      return false;
    }
    var parmas = { formId: formId, pfee: this.data.peisong, cityId: this.data.address.cityOrigin, pType: this.data.song, remarks: this.data.remaks, xie: 1, adressId: this.data.address.id, orderId: this.data.order.id };
    if (this.data.song == 1) {
      parmas.dotId = this.data.dot.id;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(self.data.yaoUrl, parmas, function (data) {
      wx.hideLoading();
      if (data.data.type == 1) {
        var order = data.data;
        wx.requestPayment({
          timeStamp: order.timeStamp,
          nonceStr: order.nonceStr,
          package: order.package,
          signType: 'MD5',
          paySign: order.paySign,
          success: function (res) {
            self.toast("支付成功");
            wx.redirectTo({
              url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
            })
          },
          fail: function (res) {
            console.log(JSON.stringify(res + "为什么失败"));
            wx.showToast({
              title: "支付失败",
              duration: 3000
            })
            wx.redirectTo({
              url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
            })
            wx.hideLoading();
          }
        })
      } else {
        wx.hideLoading()
        self.toast("支付失败");
        wx.redirectTo({
          url: '/pages/member/tab3/order/orderList?banrdId=' + self.data.banrd.id,
        })
      }
    })
  },
  remaks:function(e){
   var value=e.detail.value;
   this.setData({
     remaks:value
   })
  },
  look: function () {
    wx.navigateTo({
      url: '/pages/protocol/explain',
    })
  },
  gotoDao: function () {
    var item = this.data.dot;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图定位功能将无法使用',
            success: function (res) {
              if (res.cancel) {
                console.info("1授权失败返回数据");

              } else if (res.confirm) {
                //village_LBS(that);
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      wx.openLocation({
                        latitude: parseFloat(item.latitude),
                        longitude: parseFloat(item.longitude),
                        name: item.coordinateAddress,
                        scale: 28
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.openLocation({
            latitude: parseFloat(item.latitude),
            longitude: parseFloat(item.longitude),
            name: item.coordinateAddress,
            scale: 28
          })
        }
      }
    })
  }
})
